<?php

namespace App\Libs\Filter;

/*
 * 用法:
 * $filter = new filter
 *
 * or
 *
 * $filter = filter::instance()
        ->select('gametype',$gametype,null,array('id'=>'gametype')) //下拉列表选择
        ->HTML('筛选名称:')     //文本或者HTML源码
        ->input('gname','test')     //文本输入框
        ->br()      //br换行
        ->HTML('按添加时间')  
        ->order_by('add_time','desc')   //排序方向下拉选择
        ->HTML('排列')
        ->date('add_time_s','添加时间') //时间范围指定，两个时间文本框
        ->submit();     //提交按钮
 * 
 * /* 多级select下拉菜单
	 * $array = array(
            0=>array(
				'key'=>'',
				'value'=>'请选择'
			),
			1=>array(
				'key'=>3,
				'value'=>5,
				'sub'=>array(
					0=>array(
						'key'=>5,
						'value'=>9
					),
					1=>array(
						'key'=>9,
						'value'=>'dsufo'
					)
				)
			),
			2=>array(
				'group'=>'一级',
				'sub'=>array(
					0=>array(
						'key'=>5,
						'value'=>9
					),
				)
			)
		);
 *      $filter = filter::instance()->sub_select('sub_select',$array,null,true);//第四个参数表示有下级child的列本身是否变灰禁止选择
 * 
 * if ($filter->is_filtering()){
 *      $r = $filter->get_where();
 *      var_dump($r);
 *      结果:
 *      打印出所有搜索条件组成的数组
 * 
 *      $r = $filter->sql_where(array('add_time_s'=>'add_time'));//别名替换，最终输出的sql where语句中，以add_time为字段名
 *      var_dump($r);
 *      结果:
 *      string '`gametype` = '3' and `gname` like '%test1%' and `add_time` >= '1368547200' and `add_time` < '1368806400'' (length=104)
 * 
 *      $r = $filter->sql_order_by();
 *      var_dump($r);
 *      结果:
 *      string '`add_time` asc' (length=14)
}
 */
class Filter{
    
    private $unit = array();//搜索单元
    
    private $unit_HTML = array();//搜索单元HTML代码
    
    private static $count = 0;//搜索单元框数量
    
    private $date_timestamp_mode;
    
    private $unit_array = array();//搜索单元结果数组
    
    private static $alias_config = array(//表单name别名配置
        
    );
    
    private static $attributes_config = array(//表单控件属性配置
        'checkbox'=>null,
        'date'=>array('class'=>'form-control'),
        'input'=>array('class'=>'form-control'),
        'input_equal'=>array('class'=>'form-control'),
        'order_by'=>array('class'=>'select-search-hide'),
        'order_by_array'=>array('class'=>'select-search-hide'),
        'radio'=>null,
        'reset'=>array('class'=>'btn btn-primary'),
        'select'=>array('class'=>'select-search-hide width300'),
        'sub_select'=>null,
        'submit'=>array('class'=>'btn btn-primary'),
    );
    
    private static $filterSubmit = array(null,'搜索');//'<input type="submit" value="搜索" />';
    
    private static $filterReset = array(null,'重置');//'<input type="reset" value="重置" />';
    
    private static $My97DatePicker = 'js/My97DatePicker/WdatePicker.js';//日期选择空间路径
    
    protected static $filterFormId;

    /**
     * 获取默认表单控件属性配置
     * @param type $unit_type
     * @return type
     */
    protected static function _attributes_config($unit_type, array $value = array()){
        if ($value){
            self::$attributes_config[$unit_type] = $value;
            return self::$attributes_config;
        }
        if (isset(self::$attributes_config[$unit_type]) && is_array(self::$attributes_config[$unit_type]))
            return self::$attributes_config[$unit_type];
        return array();
    }
    
    //主体初始化
    public static function instance(){
        return new self;
    }
    
    public function __toString() {
        return $this->render();
    }
    
    /**
     * 输出
     * @return type
     */
    protected function render(){
    	$k = -1;
        //单元开始
        self::$count++;
        self::$filterFormId = 'filterForm'.self::$count;
    	$v = '<span id="'.self::$filterFormId.'">';
    	foreach ($this->unit as $name=>$unit_type){
            $v .= '<span style="margin:5px;white-space: nowrap;">';
            $v .= $this->unit_HTML[$name];
            $v .= '</span>';
    	}
    	//单元结尾
        $v .= '<input type="hidden" name="filter[filterFormCount]" value="'.self::$count.'" />';
        $v .= '</span>';

        //单元保留前次搜素条件选择
        $v .= $this->script();
        
    	return $v;
    }
    
    /**
     * br换行
     * @return \YHGCommon\Html\Filter
     */
    public function br(){
        $name = 'br_'.mt_rand();
        $this->unit[$name] = 'br';
        $this->unit_HTML[$name] = '<br />';
        return $this;
    }
    
    /**
     * 自定义内容
     * @param type $HTML
     * @return \YHGCommon\Html\Filter
     */
    public function HTML($HTML){
        if (is_string($HTML) && !empty($HTML)){
            $name = 'HTML_'.mt_rand();
            $this->unit[$name] = 'HTML';
            $this->unit_HTML[$name] = $HTML;
        }
        return $this;
    }
    
    /**
     * 单选框radio
     * @param type $name
     * @param array $options 多个选项值和文字描述关联数组
     * @param type $checked 哪些默认选中，布尔值：全选/全不选，单个数值：单个选中，数组：值在数组中的选中
     * @param array $attributes
     * @param type $wrap 结构化包裹标记html字串
     */
    public function radio($name, array $options = NULL, $checked = NULL, array $attributes = NULL,$wrap = NULL){
        $_radio = '';
        $k = 0;
        foreach ($options as $value=>$title){
            $id = "filter_{$name}_".($k++);
            $_checked = is_bool($checked) ? $checked : (is_array($checked) ? in_array($value, $checked) : ($value == $checked));
            
            $attributes = array('id'=>$id)+(array)$attributes+self::_attributes_config('radio');
            $dom = Form::radio("filter[$name]", $value, $_checked, $attributes);
            $dom .= "<label for='$id'>$title</label>";
            
            if ($wrap){
                $dom = $wrap.$dom.$this->findWrapClose($wrap);
            }
            
            $_radio .= $dom;
        }
        
        $this->unit[$name] = 'radio';
        $this->unit_HTML[$name] = $_radio;
        return $this;
    }
    
    /**
     * 复选框checkbox
     * @param type $name
     * @param array $options 多个选项值和文字描述关联数组
     * @param type $checked 哪些默认选中，布尔值：全选/全不选，单个数值：单个选中，数组：值在数组中的选中
     * @param array $attributes
     * @param type $wrap 结构化包裹标记html字串
     */
    public function checkbox($name, array $options = NULL, $checked = NULL, array $attributes = NULL,$wrap = NULL){
        $_checkbox = '';
        $k = 0;
        $mutil = (bool)preg_match('/\[\]$/', $name);
        $name = trim($name,'[]');
        foreach ($options as $value=>$title){
            $id = "filter_{$name}_".($k++);
            $_checked = is_bool($checked) ? $checked : (is_array($checked) ? in_array($value, $checked) : ($value == $checked));
            
            $attributes = array('id'=>$id)+(array)$attributes+self::_attributes_config('checkbox');
            if ($mutil){
                $dom = Form::checkbox("filter[$name][]", $value, $_checked, $attributes);
            }else{
                $dom = Form::checkbox("filter[$name]", $value, $_checked, $attributes);
            }
            $dom .= "<label for='$id'>$title</label>";
            
            if ($wrap){
                $dom = $wrap.$dom.$this->findWrapClose($wrap);
            }
            
            $_checkbox .= $dom;
        }
        
        $this->unit[$name] = 'checkbox';
        $this->unit_HTML[$name] = $_checkbox;
        return $this;
    }
    
    /**
     * 重置按钮rest
     * @param type $name
     * @param type $value
     * @param array $attributes
     * @return \YHGCommon\Html\Filter
     */
    public function reset($name = null, $value = 'Reset', array $attributes = NULL){
        if (func_num_args()){
            $attributes = array('type'=>'reset','id'=>"filter_reset")+(array)$attributes+self::_attributes_config('reset');
            $_reset = Form::input($name, $value,$attributes);
        }else{
            if (isset(self::$filterReset[2]))
                self::$filterReset[2] = array('type'=>'reset','id'=>"filter_reset")+(array)self::$filterReset[2]+self::_attributes_config('reset');
            else
                self::$filterReset[2] = array('type'=>'reset','id'=>"filter_reset")+self::_attributes_config('reset');
            $_reset = call_user_func_array(__NAMESPACE__.'\Form::input', self::$filterReset);
        }
        $this->unit['filterReset'] = 'filterReset';
        $this->unit_HTML['filterReset'] = $_reset;
        return $this;
    }
    
    /**
     * 提交搜索按钮submit
     * @param type $name
     * @param type $value
     * @param array $attributes
     * @return \YHGCommon\Html\Filter
     */
    public function submit($name = null, $value = 'Search', array $attributes = NULL){
        if (func_num_args()){
            $attributes = array('id'=>"filter_submit")+(array)$attributes+self::_attributes_config('submit');
            $_submit = Form::submit($name, $value,$attributes);
        }else{
            if (isset(self::$filterSubmit[2]))
                self::$filterSubmit[2] = array('id'=>"filter_submit")+(array)self::$filterSubmit[2]+self::_attributes_config('submit');
            else
                self::$filterSubmit[2] = array('id'=>"filter_submit")+self::_attributes_config('submit');
            $_submit = call_user_func_array(__NAMESPACE__.'\Form::submit', self::$filterSubmit);
        }
        $this->unit['filterSubmit'] = 'filterSubmit';
        $this->unit_HTML['filterSubmit'] = $_submit;
        return $this;
    }
    
    /**
     * 下拉选项select
     * @param type $name
     * @param array $options
     * @param type $selected
     * @param array $attributes
     * @return \YHGCommon\Html\Filter
     */
    public function select($name, array $options = NULL, $selected = NULL, array $attributes = NULL){
        $attributes = array('id'=>"filter_$name")+(array)$attributes+self::_attributes_config('select');
        $_select = Form::select("filter[$name]",$options, $selected, $attributes);
        $this->unit[$name] = 'select';
        $this->unit_HTML[$name] = $_select;
        return $this;
    }
    
    /**
     * 多级下拉选项select
     * @param type $name
     * @param array $options
     * @param type $selected
     * @param type $parent_disable
     * @param array $attributes
     * @return \YHGCommon\Html\Filter
     */
    public function sub_select($name, array $options = NULL, $selected = NULL, $parent_disable = NULL, array $attributes = NULL){
        $attributes = array('id'=>"filter_$name")+(array)$attributes+self::_attributes_config('select');
        $_select = HTML::select("filter[$name]",$options, $selected, $parent_disable,$attributes);
        $this->unit[$name] = 'select';
        $this->unit_HTML[$name] = $_select;
        return $this;
    }
    
    /**
     * 模糊搜索文本input text
     * @param type $name
     * @param type $value
     * @param array $attributes
     * @return \YHGCommon\Filter\Base
     */
    public function input($name, $value = NULL, array $attributes = NULL){
        $attributes = array('id'=>"filter_$name")+(array)$attributes+self::_attributes_config('input');
        $_input = Form::input("filter[$name]", $value, $attributes);
        $this->unit[$name] = 'input';
        $this->unit_HTML[$name] = $_input;
        return $this;
    }
    
    /**
     * 完全匹配搜索文本input text
     * @param type $name
     * @param type $value
     * @param array $attributes
     * @return \YHGCommon\Filter\Base
     */
    public function input_equal($name, $value = NULL, array $attributes = NULL){
        $attributes = array('id'=>"filter_$name")+(array)$attributes+self::_attributes_config('input');
        $_input = Form::input("filter[$name]", $value, $attributes);
        $this->unit[$name] = 'input_equal';
        $this->unit_HTML[$name] = $_input;
        return $this;
    }
    
    /**
     * 日期时间控件input text
     * @param type $name
     * @param type $title
     * @param type $timestamp
     * @param type $from_time
     * @param type $to_time
     * @return \YHGCommon\Filter\Base
     */
    public function datetime($name,$title = null,$timestamp = true,$from_time = null,$to_time = null){
        $this->date_timestamp_mode = (bool)$timestamp;

        if (is_int($from_time))
            $from_time = date('Y-m-d H:i:s',$from_time);
        if ($to_time){
            if (is_int($to_time))
                $to_time = date('Y-m-d H:i:s',$to_time);
        }else
            $to_time = date('Y-m-d H:i:s',strtotime('tomorrow'));

        $_date = (string)$title;

        $attributes_date_from = array('id'=>"filter_{$name}_from")+self::_attributes_config('date');
        $attributes_date_to = array('id'=>"filter_{$name}_to")+self::_attributes_config('date');
        if (self::$My97DatePicker){
            $_date .= '<script type="text/javascript" src="/'.self::$My97DatePicker.'" ></script>';
            $attributes_date_from += array('onclick'=>'WdatePicker({startDate:"%y-%M-%d 00:00:00",dateFmt:"yyyy-MM-dd HH:mm:ss"})','class'=>'Wdate');
            $attributes_date_to += array('onclick'=>'WdatePicker({startDate:"%y-%M-%d %H:%i:%m",dateFmt:"yyyy-MM-dd HH:mm:ss"})','class'=>'Wdate');
        }

        $_date_from = '从'.Form::input("filter[{$name}_from]",$from_time,$attributes_date_from);
        $_date_to = '到'.Form::input("filter[{$name}_to]",$to_time,$attributes_date_to);
        $_date .= $_date_from.$_date_to;

        $this->unit[$name] = 'date';
        $this->unit_HTML[$name] = $_date;
        return $this;
    }
    
    /**
     * 日期控件input text
     * @param type $name
     * @param type $title
     * @param type $timestamp
     * @param type $from_time
     * @param type $to_time
     * @return \YHGCommon\Filter\Base
     */
    public function date($name,$title = null,$timestamp = true,$from_time = null,$to_time = null){
        $this->date_timestamp_mode = (bool)$timestamp;

        if (is_int($from_time))
            $from_time = date('Y-m-d',$from_time);
        if ($to_time){
            if (is_int($to_time))
                $to_time = date('Y-m-d',$to_time);
        }else
            $to_time = date('Y-m-d',strtotime('tomorrow'));

        $_date = (string)$title;

        $attributes_date_from = array('id'=>"filter_{$name}_from")+self::_attributes_config('date');
        $attributes_date_to = array('id'=>"filter_{$name}_to")+self::_attributes_config('date');
        if (self::$My97DatePicker){
            $_date .= '<script type="text/javascript" src="/'.self::$My97DatePicker.'" ></script>';
            $attributes_date_from += array('onclick'=>'WdatePicker()','class'=>'Wdate');
            $attributes_date_to += array('onclick'=>'WdatePicker()','class'=>'Wdate');
        }

        $_date_from = '从'.Form::input("filter[{$name}_from]",$from_time,$attributes_date_from);
        $_date_to = '到'.Form::input("filter[{$name}_to]",$to_time,$attributes_date_to);
        $_date .= $_date_from.$_date_to;

        $this->unit[$name] = 'date';
        $this->unit_HTML[$name] = $_date;
        return $this;
    }
    
    /**
     * 排序方向select
     * @param type $name
     * @param type $direction
     * @return \YHGCommon\Filter\Base
     */
    public function order_by($name,$direction = null){
        $attributes = array('id'=>"filter_{$name}")+self::_attributes_config('order_by');
        $_order_by = Form::select("filter[$name]",array(''=>'排序','desc'=>'降序','asc'=>'升序'),$direction,$attributes);
        $this->unit[$name] = 'order_by';
        $this->unit_HTML[$name] = $_order_by;
        return $this;
    }

    /**
     * 多种排序select
     */
    /*$filter->order_by_array('gamedown',array(
        'gweekdown'=>'周',
        'gmonthdown'=>'月'
    ));*/
    public function order_by_array($name,array $option,$direction = null){
        $options = array();
        foreach ($option as $field=>$text){
            $options[$field.'_desc'] = $text.'降序';
            $options[$field.'_asc'] = $text.'升序';
        }
        $attributes = array('id'=>"filter_{$name}")+self::_attributes_config('order_by');
        $_order_by = Form::select("filter[$name]",array(''=>'排序')+$options,$direction,$attributes);
        $this->unit[$name] = 'order_by_array';
        $this->unit_HTML[$name] = $_order_by;
        return $this;
    }

    /**
     * 是否提交搜索
     * @return type
     */
    public function is_filtering(){
        return (isset($_REQUEST['filter']) && !empty($_REQUEST['filter']));
    }
    
    /**
     * 当前搜索面板索引值，从1开始
     * @return int
     */
    public function index(){
        if (!$this->is_filtering()) return 0;
        $filter = $_REQUEST['filter'];
        return (int)$filter['filterFormCount'];
    }
    
    /**
     * 找到结构化包裹的闭合标签
     * @param type $wrap
     */
    private function findWrapClose($wrap){
        $wrapClose = '';
        if (preg_match_all('/<([^\s]+)[^>]*>/', $wrap, $tags)){
            $tags = array_reverse($tags[1]);
            foreach ($tags as $tag){
                $wrapClose .= "</$tag>";
            }
        }
        return $wrapClose;
    }
    
    //自动选择前次搜索条件，搜索条件回填
    private function script(){
    	if (!$this->is_filtering()) return '';
        $count = isset($_REQUEST['filter']['filterFormCount'])?$_REQUEST['filter']['filterFormCount']:1;
        if ($count != self::$count)
            return '';
    	$v = '<script type="text/javascript">(function(){';
        $v .= <<<EOT
            var q = function (strId1, strId2) {
                var id1 = document.getElementById(strId1), id1Chidlren = id1.getElementsByTagName('*'), i = 0, len = id1Chidlren.length, id2 = null;

                for (; i < len; ++i) {
                    if (id1Chidlren[i].id === strId2) {
                        id2 = id1Chidlren[i];
                        break;
                    }
                }

                return id2;
            };
            var p = function (strId1, strName, strValue) {
                var id1 = document.getElementById(strId1), id1Chidlren = id1.getElementsByTagName('*'), i = 0, len = id1Chidlren.length, id2 = null;

                for (; i < len; ++i) {
                    if ( ( (id1Chidlren[i].name === strName) || (id1Chidlren[i].name && (id1Chidlren[i].name.replace(/(\[\])+$/g,'') === strName)) )
                        && (id1Chidlren[i].value == strValue) ) {
                        id2 = id1Chidlren[i];
                        break;
                    }
                }

                return id2;
            };
EOT;
    	foreach ($this->unit as $name=>$unit_type){
            $script = $this->scriptFactory($name,$unit_type);
            if (empty($script)){
                continue;
            }
            $v .= "\ntry{";
    		$v .= "\n".$script;
            $v .= "\n}catch(e){console.log(\"$script \" + e.name + ':' + e.message);}";
    	}
        $v .= '})();</script>';
        //$v .= '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>';
        return $v;
    }
    
    //搜索条件回填工厂方法
    private function scriptFactory($name,$unit_type){
        if (!$this->is_filtering())
            return '';
        $filter = $_REQUEST['filter'];
        $filterForm = self::$filterFormId;
        if ($unit_type == 'date'){
            if (!isset($filter[$name.'_from'])){
                $filter[$name.'_from'] = '';
            }
            if (!isset($filter[$name.'_to'])){
                $filter[$name.'_to'] = '';
            }
        }else if (!isset($filter[$name])){
            $filter[$name] = '';
        }
        switch ($unit_type){
            case 'select':
                //return "$('#{$filterForm} select[id=\"filter_{$name}\"]').val('{$filter[$name]}');\n";
                return "var d=q('{$filterForm}','filter_$name');if (d){d.value='{$filter[$name]}';};";
            case 'input':
                //return "$('#{$filterForm} input[id=\"filter_{$name}\"]').val('{$filter[$name]}');\n";
                return "var d=q('{$filterForm}','filter_$name');if (d){d.value='{$filter[$name]}';};";
            case 'input_equal':
                //return "$('#{$filterForm} input[id=\"filter_{$name}\"]').val('{$filter[$name]}');\n";
                return "var d=q('{$filterForm}','filter_$name');if (d){d.value='{$filter[$name]}';};";
            case 'date':
                //$_date_from = "$('#{$filterForm} input[id=\"filter_{$name}_from\"]').val('{$filter[$name.'_from']}');\n";
                $_date_from = "var d=q('{$filterForm}','filter_{$name}_from');if (d){d.value='{$filter[$name.'_from']}';};";
                
                //$_date_to = "$('#{$filterForm} input[id=\"filter_{$name}_to\"]').val('{$filter[$name.'_to']}');\n";
                $_date_to = "var d=q('{$filterForm}','filter_{$name}_to');if (d){d.value='{$filter[$name.'_to']}';};";
                return $_date_from.$_date_to;
            case 'order_by':
                //return "$('#{$filterForm} select[id=\"filter_{$name}\"]').val('{$filter[$name]}');\n";
                return "var d=q('{$filterForm}','filter_$name');if (d){d.value='{$filter[$name]}';};";
            case 'order_by_array':
                //return "$('#{$filterForm} select[id=\"filter_{$name}\"]').val('{$filter[$name]}');\n";
                return "var d=q('{$filterForm}','filter_$name');if (d){d.value='{$filter[$name]}';};";
            case 'radio':
                //return "$('#{$filterForm} input[id^=\"filter_{$name}\"][value=\"{$filter[$name]}\"]').attr('checked','checked');\n";
                return "var d=p('{$filterForm}','filter[{$name}]','{$filter[$name]}');if (d){d.checked=true;};";
            case 'checkbox':
                if (is_array($filter[$name])){
                    $p = '';
                    foreach ($filter[$name] as $value){
                        $p .= "var d=p('{$filterForm}','filter[{$name}][]','{$value}');if (d){d.checked=true;};";
                    }
                    return $p;
                }
                //return "$('#{$filterForm} input[id^=\"filter_{$name}\"][value=\"{$filter[$name]}\"]').attr('checked','checked');\n";
                return "var d=p('{$filterForm}','filter[{$name}]','{$filter[$name]}');if (d){d.checked=true;};";
            default:
                return '';
        }
    }
    
    /**
     * 获取最终的搜索条件数组
     * @param bool $pairs 是否返回强制关联全等的一维数组，true：是，false：否
     * @return array
     */
    public function get_where($pairs = false){
        if (!$this->is_filtering())
            return array();
        if (!empty($this->unit_array))
            return $this->unit_array;
        foreach ($this->unit as $name=>$unit_type){
            $this->unitFactory($name, $unit_type);
        }
        if ($pairs){
            $unit_array = array();
            foreach ($this->unit_array as $array){
                $unit_array[$array[0]] = $array[2];
            }
            return $unit_array;
        }
        
        return $this->unit_array;
    }
    
    /**
     * 获取最终的排序条件数组
     * @return array
     */
    public function get_order_by(){
        if (!$this->is_filtering())
            return array();
        $filter = $_REQUEST['filter'];
        $order_by = array();
        foreach ($this->unit as $name=>$unit_type){
            if (!$name)
                continue;
            if (($unit_type == 'order_by') && $filter[$name])
                $order_by[$name] = strtoupper($filter[$name]);
            if (($unit_type == 'order_by_array') && $filter[$name]){
                if (count($order_by_array = explode ('_', $filter[$name])) == 2){
                    $order_by[$order_by_array[0]] = strtoupper($order_by_array[1]);
                }
                    
            }
                
        }
        return $order_by;
    }
    
    /**
     * 获取最终的搜索条件数组工厂方法
     * @param type $name
     * @param type $unit_type
     * @return boolean
     */
    private function unitFactory($name,$unit_type){
        $filter = $_REQUEST['filter'];
        if (!isset($filter[$name])){
            $filter[$name] = '';
        }
        switch ($unit_type){
            case 'select':
                if ($filter[$name] == '')
                    return false;
                return $this->unit_array[] = array($name,'=',$filter[$name]);
            case 'input':
                $_input = trim($filter[$name]);
                if ($_input == '')
                    return false;
                $_input = implode('%',explode(' ', $_input));
                $_input = '%'.$_input.'%';
                return $this->unit_array[] = array($name,'LIKE',$_input);
            case 'input_equal':
                $_input = trim($filter[$name]);
                if ($_input == '')
                    return false;
                return $this->unit_array[] = array($name,'=',$_input);
            case 'date':
                $_date_from = isset($filter[$name.'_from']) ? trim($filter[$name.'_from']) : '';
                if ($_date_from != ''){
                    $_date_from = $this->date_timestamp_mode?strtotime($_date_from):$_date_from;
                    $this->unit_array[] = array($name,'>=',$_date_from);
                }
                $_date_to = isset($filter[$name.'_to']) ? trim($filter[$name.'_to']) : '';
                if ($_date_to != ''){
                    $_date_to = strtotime($_date_to.' +1 day');
                    $_date_to = $this->date_timestamp_mode?$_date_to:date('Y-m-d',$_date_to);
                    $this->unit_array[] = array($name,'<',$_date_to);
                }
                return true;
            case 'radio':
                if ($filter[$name] == '')
                    return false;
                return $this->unit_array[] = array($name,'=',$filter[$name]);
            case 'checkbox':
                if ($filter[$name] == '')
                    return false;
                if (is_array($filter[$name])){
                    return $this->unit_array[] = array($name,'in',$filter[$name]);
                }
                return $this->unit_array[] = array($name,'=',$filter[$name]);
            default:
                return false;
        }
    }
    
    /**
     * 获取最终的搜索条件SQL
     * @param type $alias
     * @param type $compare
     * @param type $value_swither
     * @return string
     */
    public function sql_where($alias = null,$compare = null,$value_swither = null){
        $wheres = $this->get_where();
        if (empty($wheres))
            return '';
        $_sql_where = array();
        $alias = (array)$alias+self::$alias_config;
        foreach ($wheres as $where){
            //字段别名
            if (is_callable($alias))
                $where[0] = $alias($where);
            elseif (is_array($alias) && array_key_exists($where[0], $alias))
                $where[0] = $alias[$where[0]];
            //对比符置换
            if (is_callable($compare))
                $where[1] = $compare($where);
            elseif (is_array($compare) && array_key_exists($where[0], $compare))
                $where[1] = $compare[$where[0]];
            //值置换
            if (is_callable($value_swither))
                $where[2] = $value_swither($where);
            elseif (is_array($value_swither) && array_key_exists($where[0], $value_swither))
                $where[2] = $value_swither[$where[0]];
            
            if (false === strpos($where[0],'.')){
                $where[0] = "`{$where[0]}`";
            }else{
                list($table,$field) = explode('.',$where[0]);
                $where[0] = "`{$table}`.`{$field}`";
            }
            if (strtolower($where[1]) == 'in'){
                $_sql_where[] = "$where[0] in ('".implode("', '", $where[2])."')";
            }else{
                $_sql_where[] = "$where[0] $where[1] '{$where[2]}'";
            }
        }
        return implode(' AND ', $_sql_where);
    }
    
    /**
     * 获取最终的排序条件SQL
     * @param type $alias
     * @return string
     */
    public function sql_order_by($alias = null){
        $_order_by = $this->get_order_by();
        if (empty($_order_by))
            return '';
        $_sql_order_by = array();
        $alias = (array)$alias+self::$alias_config;
        foreach ($_order_by as $field=>$direction){
            //字段别名
            if (array_key_exists($field, $alias))
                $field = $alias[$field];
            
            if (false === strpos($field,'.')){
                $field = "`{$field}`";
            }else{
                list($table,$field) = explode('.',$field);
                $field = "`{$table}`.`{$field}`";
            }
            $_sql_order_by[] = $field.' '.$direction;
        }
        return implode(',', $_sql_order_by);
    }
}